package logic

import (
	"context"
	"database/sql"

	"go-zero-mall/app/admin/cmd/rpc/internal/svc"
	"go-zero-mall/app/admin/cmd/rpc/pd"
	"go-zero-mall/app/admin/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type RoleAllocResourceLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRoleAllocResourceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RoleAllocResourceLogic {
	return &RoleAllocResourceLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 角色-分配资源
func (l *RoleAllocResourceLogic) RoleAllocResource(in *pd.UmsRoleAllocResourceReq) (*pd.Response, error) {
	err := l.svcCtx.UmsRoleResourceRelationModel.DeleteByRoleId(l.ctx, in.RoleId)
	if err != nil {
		return nil, err
	}
	for _, v := range in.ResourceId {
		d := model.UmsRoleResourceRelation{
			RoleId: sql.NullInt64{
				Int64: in.RoleId,
				Valid: true,
			},
			ResourceId: sql.NullInt64{
				Int64: v,
				Valid: true,
			},
		}
		l.svcCtx.UmsRoleResourceRelationModel.Insert(l.ctx, &d)
	}
	return &pd.Response{}, nil
}
